<?php

namespace lxs\tools;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use lxs\config\BaseStatic;


class Uploads extends BaseStatic
{

    /**
     * 本地上传
     */
    public function localUpload($file, $path = ''): bool|string
    {
        if (is_file($file)) {
            $path = $path == '' ? 'local' : $path;
            $path = $path . '/' . Carbon::now()->format('Ymd');
            $fileName = Str::random(32) . '.' . $file->getClientOriginalExtension();
            if (Storage::disk('public')->put($path . '/' . $fileName, file_get_contents($file))) {
                return '/storage/' . $path . '/' . $fileName;
            }
            return false;
        }
        return false;
    }


    /**
     * base64上传
     * @param $base64
     * @return array
     */
    public function base64Upload($base64): array
    {
        $data = explode(',', $base64);
        unset($base64);

        if (count($data) !== 2) {
            Log::error(date('Y-m-d H:i:s') . '文件格式错误: ');
            return ['code' => 400, 'message' => '文件格式错误'];
        }

        if (preg_match('/^(data:\s*image\/(\w+);base64)/', $data[0], $result)) {
            $type = $result[2];
            if (!in_array($type, array('jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
                Log::error(date('Y-m-d H:i:s') . '文件格式不在允许范围内: ');
                return ['code' => 400, 'message' => '文件格式不在允许范围内'];
            }
            $image_name = md5(uniqid()) . '.' . $result[2];
            $image_path = storage_path('app/code/');
            $image_file = $image_path . $image_name;
            if (!file_exists($image_path)) {
                mkdir($image_path, 0777, true);
            }
            //服务器文件存储路径
            try {
                if (file_put_contents($image_file, base64_decode($data[1]))) {
                    return ['code' => 200, 'message' => '成功', 'data' => ['name' => $image_name, 'path' => $image_path]];
                } else {
                    Log::error(date('Y-m-d H:i:s') . '文件保存失败: ');
                    return ['code' => 400, 'message' => '文件保存失败'];
                }
            } catch (\Exception $e) {
                return ['code' => 400, 'message' => $e->getMessage()];
            }
        }

        Log::error(date('Y-m-d H:i:s') . '文件格式错误: ');
        return ['code' => 400, 'message' => '文件格式错误'];
    }


}
